package com.hare.common.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

public class IpUtil {
    private static final String TENCENT_MAP_KEY = "ACRBZ-VNWWK-4BVJM-AWRUL-ONTTJ-YRFGN";


    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }

    /**
     * //响应示例：
     * {
     *     "status": 0,
     *     "message": "query ok",
     *     "result": {
     *         "ip": "202.106.0.30",
     *         "location": {
     *             "lng": 116.407526,
     *             "lat": 39.90403
     *         },
     *         "ad_info": {
     *             "nation": "中国",
     *             "province": "",
     *             "city": "",
     *             "adcode": 110000
     *         }
     *     }
     * }
     * @param ip
     * @return
     */
    public static Map<String,Object> getAddress(String ip){
        String urlStr = "https://apis.map.qq.com/ws/location/v1/ip?key="+TENCENT_MAP_KEY;
        String response = "";
        try {
            response = HttpRequest.get(urlStr + "&ip=" + ip)
                    .execute()
                    .body();
        } catch (Exception ex) {
        }
        return JSON.parseObject(response);
    }

    /**
     * 返回结果 参考：http://apis.map.qq.com/ws/geocoder/v1/?location=32.048677,118.797772&get_poi=1&key=ACRBZ-VNWWK-4BVJM-AWRUL-ONTTJ-YRFGN
     * @param lat
     * @param lon
     * @return
     */
    public static JSONObject getAddressByLocation(String lat,String lon){
        String urlStr = String.format("http://apis.map.qq.com/ws/geocoder/v1/?location=%s,%s&get_poi=1&key=%s"
                ,lat,lon,TENCENT_MAP_KEY);
        String response = "";
        try {
            response = HttpRequest.get(urlStr)
                    .execute()
                    .body();
        } catch (Exception ex) {
        }
        JSONObject result = JSON.parseObject(response);
        if(result.getInteger("status") == 0){
            JSONObject addressObj = result.getJSONObject("result");
            return addressObj.getJSONObject("address_component");
        }
        else{
            return new JSONObject();
        }
    }


    /**
     * 根据城市获取经纬度
     * 参考：https://apis.map.qq.com/ws/geocoder/v1/?address=%E9%83%91%E5%B7%9E%E5%B8%82&key=ACRBZ-VNWWK-4BVJM-AWRUL-ONTTJ-YRFGN
     * @param cityName
     * @return
     */
    public static JSONObject getLocationByCity(String cityName){
        String urlStr = String.format("http://apis.map.qq.com/ws/geocoder/v1/?address=%s&key=%s"
                ,cityName,TENCENT_MAP_KEY);
        String response = "";
        try {
            response = HttpRequest.get(urlStr)
                    .execute()
                    .body();
        } catch (Exception ex) {
        }
        JSONObject result = JSON.parseObject(response);
        if(result.getInteger("status") == 0){
            JSONObject addressObj = result.getJSONObject("result");
            return addressObj.getJSONObject("location");
        }
        else{
            return new JSONObject();
        }
    }
}
